import { apiClient } from "./api";
import { getCurrentUsername } from "./storage";

// ✅ 导出函数而不是对象，方便直接调用
export async function getCurrentUser() {
  const username = getCurrentUsername();
  if (!username) {
    console.warn("No current user found in storage.");
    return {
      id: -1,
      username: "Anonymous",
      avatar: "assets/images/users/user-10.jpg",
    };
  }

  try {
    const response = await apiClient.get("/users/current", {
      headers: {
        "X-Username": username,
      },
    });

    console.log("✅ 后端返回的 current user response：", response);

    return {
      id: response.userId,
      username: response.username || "Anonymous",
      email: response.email || "anonymous@example.com",
      realName: response.realName || "",
      avatar: response.avatar || "assets/images/users/user-10.jpg",
    };
  } catch (error) {
    console.error("Failed to fetch current user:", error);
    return {
      id: -1,
      username: "Anonymous",
      email: "anonymous@example.com",
      realName: "",
      avatar: "assets/images/users/user-10.jpg",
    };
  }
}

export async function updateUser(id, userData) {
  try {
    console.log("📤 正在更新用户 ID:", id);
    const response = await apiClient.put(`/users/${id}`, userData);
    return {
      id: response.userId,
      username: response.username || "Anonymous",
      email: response.email || "anonymous@example.com",
      realName: response.realName || "",
      avatar: response.avatar || "assets/images/users/user-10.jpg",
    };
  } catch (error) {
    console.error("更新用户失败：", error);
    throw error;
  }
}
